package com.ilovepostcard.view;

import com.ilovepostcard.EditImageActivity;
import com.ilovepostcard.EditTextActivity;
import com.ilovepostcard.FeedbackActivity;
import com.ilovepostcard.MessageActivity;
import com.ilovepostcard.PreviewActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.SearchActivity;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.Utils;
import com.mobclick.android.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PostcardTopBar extends RelativeLayout{

    private boolean showBack = true;
    private boolean hideToolButton = false;
    public PostcardTopBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        loadAttri(attrs);
        inflate();
    }

    public PostcardTopBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        loadAttri(attrs);
        inflate();
    }

    public PostcardTopBar(Context context) {
        super(context);
        inflate();
    }

    private void loadAttri(AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.PostcardTopbar);
        showBack = ta.getBoolean(R.styleable.PostcardTopbar_showBack, true);
        hideToolButton = ta.getBoolean(R.styleable.PostcardTopbar_hideToolButton, false);
    }
    
    private void inflate() {
        View view = View.inflate(getContext(), R.layout.postcard_topbar, this);
        View topbarBack = view.findViewById(R.id.topbar_back);
        View topbarSearch = view.findViewById(R.id.topbar_search);
        View topbarNotification = view.findViewById(R.id.topbar_notification);
        final TextView topbarNotificationCountView = (TextView) view.findViewById(R.id.topbar_notification_badge);
        final View topbarMenu = view.findViewById(R.id.topbar_menu);
        topbarBack.setVisibility(showBack? VISIBLE : GONE);
        topbarSearch.setVisibility(hideToolButton ? GONE : VISIBLE);
        topbarNotification.setVisibility(hideToolButton ? GONE : VISIBLE);
        topbarNotificationCountView.setVisibility(GONE);
        topbarMenu.setVisibility(hideToolButton ? GONE : VISIBLE);
        
        if (!hideToolButton) {
            new ServerAsyncTask(getContext()) {
                
                @Override
                protected void onSuccess(PostcardResult result) {
                    int count = result.getNewMessageCount();
                    topbarNotificationCountView.setVisibility(count > 0 ? VISIBLE : GONE);
                    topbarNotificationCountView.setText(result.getNewMessageCount()+"");
                }
                
                @Override
                protected PostcardResult doRequest() {
                    User loginUser = UserController.getLoginUser(getContext());
                    return ServerFactory.getServer().getNewMessageCount(loginUser.UserID);
                }
            }.execute();
        }
       
        topbarBack.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();
            }
        });
        topbarSearch.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();
                Intent search = new Intent( ((Activity)getContext()),SearchActivity.class);
                ((Activity)getContext()).startActivity(search);
            }
        });
        
        topbarNotification.setOnClickListener(new OnClickListener()
        {

			@Override
			public void onClick(View v) {
				Activity activity = (Activity)PostcardTopBar.this.getContext();
				Intent nextPage = new Intent(activity,MessageActivity.class);
				activity.startActivity(nextPage);
				
			}
        	
        });
        
        
        
        topbarMenu.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {

           	   /* PopupMenu popup = new PopupMenu(PostcardTopBar.this.getContext(), topbarMenu);
           	    MenuInflater inflater = popup.getMenuInflater();
           	    inflater.inflate(R.menu.menu_spinners, popup.getMenu());
           	    popup.show();*/
            	MobclickAgent.onEvent(PostcardTopBar.this.getContext(), Constants.COUNT_SPINNER);
            	LayoutInflater mLayoutInflater =((Activity)(PostcardTopBar.this.getContext())).getLayoutInflater();
            	
	            View popunwindwow = mLayoutInflater.inflate(  
	                     R.layout.menu_spinners_list, null);  
	           final PopupWindow mPopupWindow = new PopupWindow(popunwindwow, 220,  
	                     LayoutParams.WRAP_CONTENT);  
	            mPopupWindow.setFocusable(true);
	            mPopupWindow.showAsDropDown(topbarMenu); 
	            popunwindwow.setOnTouchListener(new OnTouchListener()
	            {

					@Override
					public boolean onTouch(View v, MotionEvent event) {

						
						if(mPopupWindow!= null && mPopupWindow.isShowing())
							mPopupWindow.dismiss();
						
						return false;
					}
	            	
	            });
	            
	            popunwindwow.setOnKeyListener(new OnKeyListener()
	            {

					@Override
					public boolean onKey(View v, int keyCode, KeyEvent event) {
						if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
						{
							if(mPopupWindow!= null && mPopupWindow.isShowing())
								mPopupWindow.dismiss();
						}
						return false;
					}
	            	
	            });
	            ListView items = (ListView)popunwindwow.findViewById(R.id.menu_spinners_list);
	            items.setAdapter(new ArrayAdapter<String>(PostcardTopBar.this.getContext(), R.layout.menu_spinners_listitem,(PostcardTopBar.this.getContext()).getResources().getStringArray(R.array.menu_spinners)));
	            items.setOnItemClickListener(new OnItemClickListener()
	            {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						Activity activity = (Activity)PostcardTopBar.this.getContext();
						if (arg2 == 0) {
						    Utils.checkForUpdate(getContext(),true);
						} else if(arg2 == 1) 
						{
							MobclickAgent.onEvent(PostcardTopBar.this.getContext(), Constants.COUNT_SPINNER_FEEDBACK);
							Intent nextPage = new Intent(activity,FeedbackActivity.class);
							activity.startActivity(nextPage);
						} else if (arg2 == 2) {
							MobclickAgent.onEvent(PostcardTopBar.this.getContext(), Constants.COUNT_SPINNER_FOLLOW);
						    Intent intent = new Intent(Intent.ACTION_VIEW);
						    intent.setData(Uri.parse("http://weibo.com/ilovepostcard"));
						    getContext().startActivity(intent);
						} else if (arg2 == 3) {
							MobclickAgent.onEvent(PostcardTopBar.this.getContext(), Constants.COUNT_SPINNER_INVITE);
						    Utils.inviteFriends(getContext());
						}
						mPopupWindow.dismiss();
						
						
					}
	            	
	            });

            }
        });
        
        
    }
}
